package cn.dzhang.spring.web.controler;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.dzhang.spring.model.User;
import cn.dzhang.spring.service.UserService;

@Controller
@RequestMapping("/users")
public class UserController {
	@Resource
	private UserService us;

	@RequestMapping
	public ModelAndView index() {
		return new ModelAndView("users/index", "users", us.findAll());
	}

	@RequestMapping("/edit/{id}")
	public ModelAndView edit(@PathVariable String id) {
		return new ModelAndView("users/edit", "user", us.findById(id));
	}

	@RequestMapping("/new")
	public ModelAndView create() {
		return new ModelAndView("users/new", "user", new User());
	}

	@RequestMapping(method = RequestMethod.PUT)
	public String update(@Valid User user, BindingResult result,
			RedirectAttributes attributes) {
		if (result.hasErrors()) {
			attributes.addAttribute("id", user.getId());
			return "redirect:users/edit/{id}";
		}

		us.saveOrUpdate(user);
		return "redirect:users";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String save(@Valid User user, BindingResult result,
			RedirectAttributes attributes) {
		if (result.hasErrors()) {
			return "redirect:users/new";
		}

		us.saveOrUpdate(user);
		return "redirect:users";
	}

	@RequestMapping(method = RequestMethod.POST, value = "/login")
	public String login(@RequestParam String username,
			@RequestParam String password, RedirectAttributes attributes) {
		User user = us.findByUsername(username);
		if (user == null || !password.equals(user.getPassword())) {
			attributes.addFlashAttribute("messsage", "用户名或密码不对");
			return "redirect:/login";
		}

		user.setOnline(true);
		us.saveOrUpdate(user);

		return "redirect:/";
	}

}
